import { defineStore } from 'pinia'
import {
  createDataApi,
  createUserDataApi,
  delById,
  deleteUserApi,
  editDataApi,
  editUserData,
  postPageListData,
  postUserListData
} from '@/service/main/system/system'
import type { ISystemState } from '@/stores/main/system/type'
import {useLoginStore} from "@/stores/login/index";

const useSystemStore = defineStore('system', {
  state: (): ISystemState => ({
    userList: [],
    userTotalCount: -1,
    pageList: [],
    pageTotalCount: 0
  }),
  actions: {
    clearPageList() {
      this.pageList = []
    },
    /**
     * 获取用户数据
     * @param formData
     */
    async postUserListAction(formData: any = {}) {
      const usersListRes = await postUserListData(formData)

      const { totalcount, list } = usersListRes.data
      this.userTotalCount = totalcount
      this.userList = list
    },
    /**
     * 删除用户
     * @param id
     */
    async deleteUserByIdAction(id: number) {
      await deleteUserApi(id)

      this.postUserListAction()
    },
    // 创建新用户
    async createUserDataAction(userInfo: any) {
      const res = await createUserDataApi(userInfo)

      this.postUserListAction({ pagesize: 10, pagenum: 1 })
    },
    // 更新用户数据
    async editUserDataAction(id: number, userInfo: any) {
      const editRes = await editUserData(id, userInfo)
    },

    // 针对不同的页面请求不同的网络数据
    async postPageListAction(pageName: string, queryInfo: any) {
      const pageListRes = await postPageListData(pageName, queryInfo)

      const { totalCount, list } = pageListRes.data

      this.pageList = list
      this.pageTotalCount = totalCount
    },

    // 不同页面删除数据请求
    delByIdAction(pageName: string, id: number): Promise<unknown> {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise<void>(async (resolve, reject) => {
        const delRes = await delById(pageName, id)

        await this.postPageListAction(pageName, { pagesize: 10, pagenum: 1 })

        resolve()
      })

    },

    // 不同页面更新表格数据
    async createDataAction(pageName: string, pageInfo: any) {
      await createDataApi(pageName, pageInfo)

      this.postPageListAction(pageName, { pagesize: 10, pagenum: 1 })
    },

    async editDataAction(pageName: string, id: number, pageInfo: any) {
      await editDataApi(pageName, id, pageInfo)

      this.postPageListAction(pageName, { pagesize: 10, pagenum: 1 })
    }
  }
})

export default useSystemStore
